import java.util.Arrays;

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}








public class project {
    public TreeNode constructFromPrePost(int[] preorder, int[] postorder) {
        if(preorder==null||preorder.length==0){
            return null;
        }
        return dfs(preorder,postorder);
    }
    public TreeNode dfs(int[] pre,int[] pos){
        if(pre==null||pre.length==0){
            return null;
        }
        if(pre.length==1){
            return new TreeNode(pre[0]);
        }
        int len=pre.length;
        TreeNode root=new TreeNode(pre[0]);
        for(int i=0;i<pos.length;i++){
            if(pre[1]==pos[i]){
                int index=i+1;
                int[] preLeft= Arrays.copyOfRange(pre,1,index+1);
                int[] preRight=Arrays.copyOfRange(pre,index+1,len);
                int[] posLeft=Arrays.copyOfRange(pos,0,index);
                int[] posRight=Arrays.copyOfRange(pos,index,len-1);
                root.left=dfs(preLeft,posLeft);
                root.right=dfs(preRight,posRight);
                break;
            }
        }
        return root;
    }
}
